<template>
    <div class="app-container">
        <!-- 条件搜索 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="退货编号" prop="stoId">
                <el-input v-model="pagin.search.stoId" placeholder="请输入退货编号" clearable @keyup.enter="handleQuery"
                    style="width: 200px;" />
            </el-form-item>
            <el-form-item label="订单编号" prop="stoProId">
                <el-input v-model="pagin.search.stoProId" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery"
                    style="width: 200px;" />
            </el-form-item>
            <el-form-item label="退货时间" prop="stoDate">
                <el-select v-model="pagin.search.stoDate" placeholder="请选择" clearable style="width: 200px;">
                    <el-option v-for="dict in dataList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="审批状态" prop="stoStatus">
                <el-select v-model="pagin.search.stoStatus" placeholder="请选择" clearable style="width: 200px;">
                    <el-option v-for="dict in tatusList" :key="dict.typeId" :label="dict.typeName"
                        :value="dict.typeId" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple"
                    @click="handleDeleteList">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格展示 -->
        <el-table v-loading="loading" :data="RtaList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="stoId" label="退货编号"></el-table-column>
            <el-table-column prop="stoProId" label="订单编号"></el-table-column>
            <el-table-column prop="stoDate" label="退货时间"></el-table-column>
            <el-table-column prop="stoActorName" label="操作人"></el-table-column>
            <el-table-column label="审批状态" prop="stoStatus" :formatter="row => getStatusNameById(row.stoStatus)">
            </el-table-column>
            <el-table-column prop="stoNote" label="备注"></el-table-column>
            <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip content="查询" placement="top">
                        <el-button type="text" icon="Search" @click="handleCheckGoods(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="修改" placement="top">
                        <el-button type="text" icon="Edit" @click="RtaUpdate(scope.row)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button type="text" icon="Delete" @click="RtaDelete(scope.row)"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!--分页组件-->
        <div class="pagination-container">
            <el-pagination class="pagiantion" @current-change="handleCurrentChange" :current-page="pagin.page"
                :page-size="pagin.count" layout="total, prev, pager, next, jumper" :total="pagin.total">
            </el-pagination>
        </div>
        <!-- 添加或修改退货单对话框 -->
        <el-dialog v-if="open" :title="title" v-model="open" append-to-body>
            <el-form ref="RtaRef" :model="rta" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="退货编号" prop="stoId">
                            <el-input v-model="rta.stoId" maxlength="20" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单编号" prop="stoProId">
                            <el-input v-model="rta.stoProId" placeholder="请输入订单编号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="退货时间" prop="stoDate">
                            <el-date-picker v-model="rta.stoDate" type="date" placeholder="选择退货日期"
                                :picker-options="{ firstDayOfWeek: 1 }" :style="{ width: '100%' }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="操作人" prop="stoActor">
                            <el-select v-model="rta.stoActor" placeholder="请选择" clearable :style="{ width: '100%' }">
                                <el-option v-for="dict in ApproverOptions" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="审批状态" prop="stoStatus">
                            <el-select v-model="rta.stoStatus" placeholder="请选择" clearable>
                                <el-option v-for="dict in statusList" :key="dict.value" :label="dict.value"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="退货备注" prop="stoNote">
                            <el-input v-model="rta.stoNote" type="textarea" placeholder="请输入备注" maxlength="200"
                                :rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="RtaFrom">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 展示物品明细的弹框 -->
        <el-dialog v-if="openTwo" :title="titleTwo" v-model="openTwo" width="1000px" append-to-body>
            <!-- 物品明细搜索表单 -->
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="商品编号" prop="productId">
                    <el-input v-model="queryParams.productId" placeholder="请输入商品编号" clearable style="width: 240px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable style="width: 240px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="OrderQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 增删按钮 -->
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleOpen('add')">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" :disabled="multiple"
                        @click="batch_handleDelete">删除</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache">刷新缓存</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <!-- 物品明细表格 -->
            <el-table v-loading="OrderLoading" :data="GoodsList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="商品编号" align="center" prop="productId" />
                <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
                <el-table-column label="商品类型" align="center" prop="productType" :show-overflow-tooltip="true" />
                <el-table-column label="商品品牌" align="center" prop="brand" />
                <el-table-column label="采购数量" align="center" prop="purchaseQuantity" />
                <el-table-column label="采购单价" align="center" prop="purchaseUnitPrice" />
                <el-table-column label="备注" align="center" prop="note" />
            </el-table>

            <!-- 分页插件 -->
            <pagination v-show="GoodsTotal > 0" :total="GoodsTotal" v-model:page="queryParams.page"
                v-model:limit="queryParams.count" @pagination="handleCheckGoods" />
        </el-dialog>

    </div>
</template>

<script setup name="Dept">
import { listRta, molRta, delRta, getRtaById, getApprover } from "@/api/procurement/rta";
import { findTatus } from "@/api/reserve/insto";
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import { queryGoodsList } from "@/api/procurement/proclist";
const { proxy } = getCurrentInstance();
const RtaList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const open = ref(false);
const title = ref("");
const openTwo = ref(false);
const titleTwo = ref("");
const ApproverOptions = ref([]);
const GoodsList = ref([]);
const tatusList = ref([]);
const data = reactive({
    rta: {

    },

    queryParams: {
        page: 1,
        total: 10,
        count: 5,
        search: {
            inventoryCountId: undefined,
        },
    },

    dataList: [
        { label: '一天内', value: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString().split('T')[0] },
        { label: '三天内', value: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).toISOString().split('T')[0] },
        { label: '一周内', value: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7).toISOString().split('T')[0] },
        { label: '半个月内', value: new Date(Date.now() - 1000 * 60 * 60 * 24 * 15).toISOString().split('T')[0] },
        { label: '一个月内', value: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).toISOString().split('T')[0] },
    ],
    OrderCondition: {
        page: 1,
        count: 5,
        maxPage: 0,
        total: 0,
        index: 0,
        search: {
            productId: undefined,
            stoProId: undefined,
            productName: undefined,
            productType: undefined,
            brand: undefined,
            purchaseQuantity: undefined,
            purchaseUnitPrice: undefined,
            note: undefined,
        },
    },

    pagin: {
        page: 1,
        total: 10,
        count: 5,
        search: {
            stoId: undefined,
            stoProId: undefined,
            stoDate: undefined,
            stoStatus: undefined,
        },
    },
    rules: {
        warehouseId: [
            { required: true, message: "仓库不能为空", trigger: "blur" },
        ],

    },
});

const { OrderCondition, queryParams, statusList, rta, rules, pagin, dataList } = toRefs(data);

/** 查询退货列表 */
function getList() {
    loading.value = true;
    listRta(pagin.value).then(response => {
        RtaList.value = response.data.list;
        pagin.value.page = response.data.pageNum;
        pagin.value.total = response.data.total;
        loading.value = false;
    });
}
// 审批人下拉列表
function ApproverList() {
    getApprover().then(response => {
        ApproverOptions.value = response.data;
    }).catch(error => {
        console.error('Failed to fetch warehouse data:', error);
    });
}
//审批状态
function tatus() {
    findTatus().then(response => {
        tatusList.value = response.data;
        getList();
    })
}
/** 取消按钮 */
function cancel() {
    open.value = false;
    rta.value = {};
}
//切换页码
function handleCurrentChange(currentPage) {
    pagin.value.page = currentPage; // 更新当前页码
    //执行查询
    getList();
}
/** 搜索按钮操作 */
function handleQuery() {
    getList();
}

/** 退货修改按钮操作 */
function RtaUpdate(row) {
    ApproverList();
    getRtaById(row.stoId).then(response => {
        rta.value = response.data;
        open.value = true;
        title.value = "修改退货单";
    });
}
/** 退货单提交按钮 */
function RtaFrom() {
    proxy.$refs["RtaRef"].validate(valid => {
        rta.value = {
            search: rta.value
        }
        if (valid) {
            if (rta.value.search.stoId != undefined) {
                molRta(rta.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    rta.value = {};
                    open.value = false;
                    getList();
                });

            } else {

                // addCheck(form.value).then(response => {
                //    proxy.$modal.msgSuccess("新增成功");
                //    form.value = {};
                //    open.value = false;
                //    getList();
                // });

            }
        }
    });
}

/** 删除退货单按钮操作 */
function RtaDelete(row) {
    proxy.$modal.confirm('是否确认删除名称为"' + row.stoId + '"的数据项?').then(function () {
        return delRta(row.stoId);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}
/**查看物品明细 */
function handleCheckGoods(row) {
    openTwo.value = true;
    titleTwo.value = "物品详单";
    OrderCondition.value.page = queryParams.value.page;
    OrderCondition.value.count = queryParams.value.count;
    OrderCondition.value.search.stoProId = row.stoProId;
    queryGoodsList(OrderCondition.value).then((response) => {
        GoodsList.value = response.data.list;
        GoodsTotal.value = response.data.total;
    });
}
/**搜索物品详情表格信息 */
function OrderQuery() {
    OrderCondition.value.search.productId = queryParams.value.productId;
    OrderCondition.value.search.productName = queryParams.value.productName;
    queryGoodsList(OrderCondition.value).then((response) => {
        GoodsList.value = response.data.list;
        GoodsTotal.value = response.data.total;
        clearForm();
    });
}
// 清空表单
const clearForm = () => {
    OrderCondition.value.search.productId = undefined;
    OrderCondition.value.search.productName = undefined;
    OrderCondition.value.search.productType = undefined;
    OrderCondition.value.search.brand = undefined;
    OrderCondition.value.search.purchaseQuantity = undefined;
    OrderCondition.value.search.purchaseUnitPrice = undefined;
    OrderCondition.value.search.note = undefined;
};

function getStatusNameById(cellValue) {
    for (const status of tatusList.value) {
        if (status.typeId == cellValue) {
            console.log(status.typeName)
            return status.typeName;
        }
    }
    // 如果没有找到匹配的项，可以返回一个默认值或者null
    return null; // 或者 'Unknown', 或者其他你认为合适的值
}
tatus();
// setInterval(getList, 10000);
// onBeforeUnmount(() => {
//     // 清除定时器
//     clearInterval(setInterval(getList, 10000));
// });
</script>